
package cs342.group1.messenger;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.sql.Date;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class CloudHelper {
	public final String CLOUD = "http://softeng.cs.uwosh.edu/students/cs342g1/";
	public final String FILE_NAME = "CloudZip.gz";
	public final String FILE_LOCATION = "/data/data/" + FILE_NAME;
	
	public static int bufferSize = 1024;

		public boolean CheckUsernameExists(String username){
			String result = "empty";
			HttpClient httpclient = new DefaultHttpClient();
	        HttpPost httppost = new HttpPost(CLOUD + "CheckUsernameExists.php");

			String xml = "<node><username>" + username + "</username></node>";
			try {
				StringEntity entity = new StringEntity(xml, "UTF-8");
				httppost.setEntity(entity); 
	            httppost.addHeader("Accept", "application/xml");
	            httppost.addHeader("Content-Type", "application/xml");
	            HttpResponse response = httpclient.execute(httppost);
	            HttpEntity responseEntity= response.getEntity();
	            String xmlString = EntityUtils.toString(responseEntity);
	            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	            DocumentBuilder db = factory.newDocumentBuilder();
	            InputSource inStream = new InputSource();
	            inStream.setCharacterStream(new StringReader(xmlString));
	            Document doc = db.parse(inStream);
	            
	            
	            NodeList nl = doc.getElementsByTagName("loginMessage");
	            for(int i = 0; i < nl.getLength(); i++) {
	                if (nl.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
	                     org.w3c.dom.Element nameElement = (org.w3c.dom.Element) nl.item(i);
	                     result = nameElement.getFirstChild().getNodeValue().trim();
	                 }
	            }

			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(result.equals("failure")){
				return false;
			}else{
				return true;
			}
		}
		
		public int InsertNewUser(String username, String hashedPW, String salt){
			int result = -1;
			HttpClient httpclient = new DefaultHttpClient();
	        HttpPost httppost = new HttpPost(CLOUD + "InsertNewUser.php");

			String xml = "<node><username>" + username + "</username><password>" + hashedPW + "</password><salt>" + salt + "</salt></node>";
			try {
				StringEntity entity = new StringEntity(xml, "UTF-8");
				httppost.setEntity(entity); 
	            httppost.addHeader("Accept", "application/xml");
	            httppost.addHeader("Content-Type", "application/xml");
	            HttpResponse response = httpclient.execute(httppost);
	            HttpEntity responseEntity= response.getEntity();
	            String xmlString = EntityUtils.toString(responseEntity);
	            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	            DocumentBuilder db = factory.newDocumentBuilder();
	            InputSource inStream = new InputSource();
	            inStream.setCharacterStream(new StringReader(xmlString));
	            Document doc = db.parse(inStream);
	            
	            
	            NodeList nl = doc.getElementsByTagName("insertId");
	            for(int i = 0; i < nl.getLength(); i++) {
	                if (nl.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
	                     org.w3c.dom.Element nameElement = (org.w3c.dom.Element) nl.item(i);
	                     result = Integer.parseInt(nameElement.getFirstChild().getNodeValue().trim());
	                 }
	            }

			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(result);
			return result;
		}
		
		public int CheckUsernamePasswordValid(String username, String password){
			int userId = -1;
			String user = "";
			String pw = "";
			String salt = "";
			HttpClient httpclient = new DefaultHttpClient();
	        HttpPost httppost = new HttpPost(CLOUD + "GetUsernamePasswordSalt.php");

			String xml = "<node><username>" + username + "</username></node>";
			try {
				StringEntity entity = new StringEntity(xml, "UTF-8");
				httppost.setEntity(entity); 
	            httppost.addHeader("Accept", "application/xml");
	            httppost.addHeader("Content-Type", "application/xml");
	            HttpResponse response = httpclient.execute(httppost);
	            HttpEntity responseEntity= response.getEntity();
	            String xmlString = EntityUtils.toString(responseEntity);
	            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	            DocumentBuilder db = factory.newDocumentBuilder();
	            InputSource inStream = new InputSource();
	            inStream.setCharacterStream(new StringReader(xmlString));
	            Document doc = db.parse(inStream);
	            
	            
	            NodeList nl = doc.getElementsByTagName("u");
	            for(int i = 0; i < nl.getLength(); i++) {
	                if (nl.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
	                     org.w3c.dom.Element nameElement = (org.w3c.dom.Element) nl.item(i);
	                     user = nameElement.getFirstChild().getNodeValue().trim();
	                 }
	            }
	            NodeList n2 = doc.getElementsByTagName("p");
	            for(int i = 0; i < n2.getLength(); i++) {
	                if (n2.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
	                     org.w3c.dom.Element nameElement = (org.w3c.dom.Element) n2.item(i);
	                     pw = nameElement.getFirstChild().getNodeValue().trim();
	                 }
	            }
	            NodeList n3 = doc.getElementsByTagName("s");
	            for(int i = 0; i < n3.getLength(); i++) {
	                if (n3.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
	                     org.w3c.dom.Element nameElement = (org.w3c.dom.Element) n3.item(i);
	                     salt = nameElement.getFirstChild().getNodeValue().trim();
	                 }
	            }
	            NodeList n4 = doc.getElementsByTagName("i");
	            for(int i = 0; i < n4.getLength(); i++) {
	                if (n4.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
	                     org.w3c.dom.Element nameElement = (org.w3c.dom.Element) n4.item(i);
	                     userId = Integer.parseInt(nameElement.getFirstChild().getNodeValue().trim());
	                 }
	            }

			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch(Exception e){
				return -1;
			}
			String newPw = PasswordHasher.md5(password + salt);
			boolean same = newPw.equalsIgnoreCase(pw);
			
			return (same ? userId : -1);
		}
		
		public Message[] GetAllMessagesForUser(int userId){
			Message[] messages = null;
			HttpClient httpclient = new DefaultHttpClient();
	        HttpPost httppost = new HttpPost(CLOUD + "GetConversations.php");

			String xml = "<node><userId>" + userId + "</userId></node>";
			try {
				StringEntity entity = new StringEntity(xml, "UTF-8");
				httppost.setEntity(entity); 
	            httppost.addHeader("Accept", "application/xml");
	            httppost.addHeader("Content-Type", "application/xml");
	            HttpResponse response = httpclient.execute(httppost);
	            HttpEntity responseEntity= response.getEntity();
	            String xmlString = EntityUtils.toString(responseEntity);
	            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	            DocumentBuilder db = factory.newDocumentBuilder();
	            InputSource inStream = new InputSource();
	            inStream.setCharacterStream(new StringReader(xmlString));
	            Document doc = db.parse(inStream);
	            
	            
	            NodeList nl = doc.getElementsByTagName("newmessage");
	            messages = new Message[nl.getLength()];
	            for(int i = 0; i < nl.getLength(); i++) {
                    	 Message message = new Message();
	                     Element element = (Element) nl.item(i);
	                     
	                     NodeList nId = element.getElementsByTagName("id");
	                     Element eId = (Element) nId.item(0);
	                     message.CloudId = Integer.parseInt(eId.getFirstChild().getTextContent().replace("\n", ""));
	                     
	                     NodeList ntoId = element.getElementsByTagName("toid");
	                     Element etoId = (Element) ntoId.item(0);
	                     message.ToUserId = Integer.parseInt(etoId.getFirstChild().getTextContent().replace("\n", ""));
	                     
	                     NodeList nfromId = element.getElementsByTagName("fromid");
	                     Element efromId = (Element) nfromId.item(0);
	                     message.FromUserId = Integer.parseInt(efromId.getFirstChild().getTextContent().replace("\n", ""));
	                     
	                     NodeList ntoname = element.getElementsByTagName("toname");
	                     Element etoname = (Element) ntoname.item(0);
	                     message.ToUserName = etoname.getFirstChild().getTextContent().replace("\n", "");
	                     
	                     NodeList nfromname = element.getElementsByTagName("fromname");
	                     Element efromname = (Element) nfromname.item(0);
	                     message.FromUserName = efromname.getFirstChild().getTextContent().replace("\n", "");
	                     
	                     NodeList nmessage = element.getElementsByTagName("message");
	                     Element emessage = (Element) nmessage.item(0);
	                     message.Message = emessage.getFirstChild().getTextContent().replace("\n", "");
	                     
	                     NodeList ndate = element.getElementsByTagName("date");
	                     Element edate = (Element) ndate.item(0);
	                     message.DateSend = new Date(java.sql.Timestamp.valueOf(edate.getFirstChild().getTextContent().replace("\n", "")).getTime());
	                     
	                     NodeList ntokeep = element.getElementsByTagName("tokeep");
	                     Element etokeep = (Element) ntokeep.item(0);
	                     message.ToKeep = etokeep.getFirstChild().getTextContent().replace("\n", "").equals("1") ? true : false;
	                     
	                     NodeList nfromkeep = element.getElementsByTagName("fromkeep");
	                     Element efromkeep = (Element) nfromkeep.item(0);
	                     message.FromKeep = efromkeep.getFirstChild().getTextContent().replace("\n", "").equals("1") ? true : false;
	                 
	                     messages[i] = message;
	              }

			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return messages;
		}
		
		public int SendNewMessage(int FromCloudId, String username, String message){
			//First check if the given username exists in the database
			int ToCloudId = -1;
			HttpClient httpclient = new DefaultHttpClient();
	        HttpPost httppost = new HttpPost(CLOUD + "GetUsernamePasswordSalt.php");

			String xml = "<node><username>" + username + "</username></node>";
			try {
				StringEntity entity = new StringEntity(xml, "UTF-8");
				httppost.setEntity(entity); 
	            httppost.addHeader("Accept", "application/xml");
	            httppost.addHeader("Content-Type", "application/xml");
	            HttpResponse response = httpclient.execute(httppost);
	            HttpEntity responseEntity= response.getEntity();
	            String xmlString = EntityUtils.toString(responseEntity);
	            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	            DocumentBuilder db = factory.newDocumentBuilder();
	            InputSource inStream = new InputSource();
	            inStream.setCharacterStream(new StringReader(xmlString));
	            Document doc = db.parse(inStream);
	            
	            NodeList n4 = doc.getElementsByTagName("i");
	            for(int i = 0; i < n4.getLength(); i++) {
	                if (n4.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
	                     org.w3c.dom.Element nameElement = (org.w3c.dom.Element) n4.item(i);
	                     if(nameElement.getFirstChild() != null){
	                    	 ToCloudId = Integer.parseInt(nameElement.getFirstChild().getNodeValue().trim());
	                     }
	                 }
	            }

			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			if(ToCloudId > 0){
				//valid username, we can now insert the message
				
				HttpClient httpclient2 = new DefaultHttpClient();
		        HttpPost httppost2 = new HttpPost(CLOUD + "SendMessage.php");

				String xml2 = "<node><toUserId>" + ToCloudId + "</toUserId><fromUserId>" + FromCloudId + "</fromUserId><message>" + message + "</message></node>";
				try {
					StringEntity entity = new StringEntity(xml2, "UTF-8");
					httppost2.setEntity(entity); 
					httppost2.addHeader("Accept", "application/xml");
					httppost2.addHeader("Content-Type", "application/xml");
		            HttpResponse response = httpclient2.execute(httppost2);
		            HttpEntity responseEntity= response.getEntity();
		            String xmlString = EntityUtils.toString(responseEntity);
		            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		            DocumentBuilder db = factory.newDocumentBuilder();
		            InputSource inStream = new InputSource();
		            inStream.setCharacterStream(new StringReader(xmlString));
		            Document doc = db.parse(inStream);

				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (ParserConfigurationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SAXException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				return ToCloudId;
			}
			else{
				//username does not exists, just return the bad id
				return ToCloudId;
			}
		}
		
		public int SendMessage(int myId, int theirId, String message){
			HttpClient httpclient2 = new DefaultHttpClient();
	        HttpPost httppost2 = new HttpPost(CLOUD + "SendMessage.php");
	        int messageId = -1;

			String xml2 = "<node><toUserId>" + theirId + "</toUserId><fromUserId>" + myId + "</fromUserId><message>" + message + "</message></node>";
			try {
				StringEntity entity = new StringEntity(xml2, "UTF-8");
				httppost2.setEntity(entity); 
				httppost2.addHeader("Accept", "application/xml");
				httppost2.addHeader("Content-Type", "application/xml");
	            HttpResponse response = httpclient2.execute(httppost2);
	            HttpEntity responseEntity= response.getEntity();
	            String xmlString = EntityUtils.toString(responseEntity);
	            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	            DocumentBuilder db = factory.newDocumentBuilder();
	            InputSource inStream = new InputSource();
	            inStream.setCharacterStream(new StringReader(xmlString));
	            Document doc = db.parse(inStream);
	            
	            NodeList n4 = doc.getElementsByTagName("insertId");
	            for(int i = 0; i < n4.getLength(); i++) {
	                if (n4.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
	                     org.w3c.dom.Element nameElement = (org.w3c.dom.Element) n4.item(i);
	                     if(nameElement.getFirstChild() != null){
	                    	 messageId = Integer.parseInt(nameElement.getFirstChild().getNodeValue().trim());
	                     }
	                 }
	            }

			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return messageId;
		}
		
		public boolean SaveMessageText(int messageId, boolean fromKeep){
			HttpClient httpclient = new DefaultHttpClient();
	        HttpPost httppost = new HttpPost(CLOUD + "SaveMessage.php");

			String xml = "<node><id>" + messageId + "</id><fromKeep>" + (fromKeep? 1 : 0) + "</fromKeep><toKeep>" + (fromKeep? 0 : 1) + "</toKeep></node>";
			try {
				StringEntity entity = new StringEntity(xml, "UTF-8");
				httppost.setEntity(entity); 
	            httppost.addHeader("Accept", "application/xml");
	            httppost.addHeader("Content-Type", "application/xml");
	            HttpResponse response = httpclient.execute(httppost);
	            HttpEntity responseEntity= response.getEntity();
	            String xmlString = EntityUtils.toString(responseEntity);
	            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	            DocumentBuilder db = factory.newDocumentBuilder();
	            InputSource inStream = new InputSource();
	            inStream.setCharacterStream(new StringReader(xmlString));
	            Document doc = db.parse(inStream);

			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return true;
		}
		
		public boolean UnsaveMessageText(int messageId){
			HttpClient httpclient = new DefaultHttpClient();
	        HttpPost httppost = new HttpPost(CLOUD + "SaveMessage.php");

			String xml = "<node><id>" + messageId + "</id><fromKeep>" + 0 + "</fromKeep><toKeep>" + 0 + "</toKeep></node>";
			try {
				StringEntity entity = new StringEntity(xml, "UTF-8");
				httppost.setEntity(entity); 
	            httppost.addHeader("Accept", "application/xml");
	            httppost.addHeader("Content-Type", "application/xml");
	            HttpResponse response = httpclient.execute(httppost);
	            HttpEntity responseEntity= response.getEntity();
	            String xmlString = EntityUtils.toString(responseEntity);
	            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	            DocumentBuilder db = factory.newDocumentBuilder();
	            InputSource inStream = new InputSource();
	            inStream.setCharacterStream(new StringReader(xmlString));
	            Document doc = db.parse(inStream);

			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return true;
		}
		
		public int GetMessageCount(int userId){
			HttpClient httpclient = new DefaultHttpClient();
	        HttpPost httppost = new HttpPost(CLOUD + "MessageCount.php");
	        int messageCount = -1;

			String xml = "<node><userId>" + userId + "</userId></node>";
			try {
				StringEntity entity = new StringEntity(xml, "UTF-8");
				httppost.setEntity(entity); 
	            httppost.addHeader("Accept", "application/xml");
	            httppost.addHeader("Content-Type", "application/xml");
	            HttpResponse response = httpclient.execute(httppost);
	            HttpEntity responseEntity= response.getEntity();
	            String xmlString = EntityUtils.toString(responseEntity);
	            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	            DocumentBuilder db = factory.newDocumentBuilder();
	            InputSource inStream = new InputSource();
	            inStream.setCharacterStream(new StringReader(xmlString));
	            Document doc = db.parse(inStream);
	            
	            NodeList n4 = doc.getElementsByTagName("messages");
	            for(int i = 0; i < n4.getLength(); i++) {
	                if (n4.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
	                     org.w3c.dom.Element nameElement = (org.w3c.dom.Element) n4.item(i);
	                     if(nameElement.getFirstChild() != null){
	                    	 messageCount = Integer.parseInt(nameElement.getFirstChild().getNodeValue().trim());
	                     }
	                 }
	            }

			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return messageCount;
		}
	
}
